const db = uniCloud.database()
exports.main = async (event, context) => {
  const { id, type } = event
  const userId = context.APPID || context.UNID

  // 检查是否已投票
  const checkRes = await db.collection('topics_records')
    .where({
      topicId: id,
      userId
    })
    .get()

  if (checkRes.data.length > 0) {
    throw new Error('您已经投过票了')
  }

  // 更新投票数
  const updateData = type === 'like' 
    ? { likes: db.command.inc(1) } 
    : { dislikes: db.command.inc(1) }
  
  await db.collection('topics').doc(id).update(updateData)

  // 添加投票记录（记录投票类型）
  await db.collection('topics_records').add({
    topicId: id,
    userId,
    type,
    createTime: Date.now()
  })

  return { success: true }
}